<!--
 * @Author: ‘wanglulu’ ‘wanglulu@ieforever.com’
 * @Date: 2023-06-26 18:30:07
 * @LastEditors: ‘wanglulu’ ‘wanglulu@ieforever.com’
 * @LastEditTime: 2023-06-26 19:53:32
 * @FilePath: \video-m3u8\src\components\videoTest.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="test-videojs">
    <el-row>
      <el-col :span="12">
        <video id="videoPlayer" class="video-js"></video>
      </el-col>
      <el-col :span="12" style="text-align: left">
        <el-button
          type="danger"
          v-for="item in urls"
          :key="item"
          @click="changeSource(item)"
          class="btn"
          >切换 {{ item }}</el-button
        >
      </el-col>
    </el-row>
  </div>
</template>
<script>
export default {
  name: "test-video-player3",
  data() {
    return {
      nowPlayVideoUrl:
        "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8",
      urls: [
        "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8",
        "http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8",
        "http://ivi.bupt.edu.cn/hls/btv2hd.m3u8   ",
      ],
      options: {
        autoplay: true, // 设置自动播放
        muted: true, // 设置了它为true，才可实现自动播放,同时视频也被静音 （Chrome66及以上版本，禁止音视频的自动播放）
        preload: "auto", // 预加载
        controls: true, // 显示播放的控件
      },
      player: null,
    };
  },
  mounted() {
    this.getVideo(this.nowPlayVideoUrl);
  },
  methods: {
    getVideo(nowPlayVideoUrl) {
      this.player = this.$video("videoPlayer", this.options);
      //关键代码， 动态设置src，才可实现换台操作
      this.player.src([
        {
          src: nowPlayVideoUrl,
          type: "application/x-mpegURL", // 告诉videojs,这是一个hls流
        },
      ]);
    },
    changeSource() {
      this.nowPlayVideoUrl =
        this.nowPlayVideoUrl === this.urls[1] ? this.urls[0] : this.urls[1];
      console.log(this.nowPlayVideoUrl, "改变了");
      // this.player.dispose();
      // this.getVideo(this.nowPlayVideoUrl);
    },
  },
  watch: {
    nowPlayVideoUrl(newVal) {
      this.getVideo(newVal);
    },
  },
  beforeDestroy() {
    if (this.player) {
      this.player.dispose(); // Removing Players,该方法会重置videojs的内部状态并移除dom
    }
  },
};
</script>
<style lang="scss">
#videoPlayer {
  width: 500px;
  height: 300px;
  margin: 50px auto;
}

.btn {
  margin-top: 10px !important;
}
</style>